<?php

namespace App\Models\Sample;

use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;

class SampleType extends BaseModel
{

    protected $table = 'sample_types';
    protected $fillable = [
        'code', 'title', 'description', 'rank', 'state', 'is_judged', 'created_by', 'updated_by', 'data_scope',
    ];
    public $sorters = ['rank'];
    public $params = ['code', 'title'];

    public function createdBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'created_by');
    }

    public function updatedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'created_by');
    }

    /**
     * 添加样本类型
     * @param $data
     * @return mixed
     */
    public function addType($data)
    {
        $userId = Auth::id();
        $data['state'] = 1;
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();
        return $this->create($data);
    }

    /**
     * 编辑样本类型
     * @param $data
     * @param $id
     * @return null
     */
    public function editType($data, $id)
    {
        $model = $this->find($id);
        if (!$model) {
            return null;
        }

        $data['updated_by'] = Auth::id();
        return $model->updateOrCreate(['id' => $id], $data);
    }

    /**
     * 获取样本类型列表
     * @param $limit
     * @param $sorter
     * @param $search
     * @param $defaultSorter
     * @return mixed
     */
    public function getTypeList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'desc') {
            $model = $this->orderBy('created_at', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->with(['createdBy:id,username', 'updatedBy:id,username'])
            ->select(['id', 'code', 'title', 'description', 'rank', 'state', 'is_judged', 'created_by', 'updated_by', 'created_at', 'updated_at']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                case 'title':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }

    /**
     * 获取指定样本类型
     * @param $id
     */
    public function getType($id)
    {
        $model = $this->with(['createdBy:id,username', 'updatedBy:id,username'])->find($id, ['id', 'code', 'title', 'description', 'rank', 'state', 'is_judged', 'created_by', 'updated_by', 'created_at', 'updated_at']);
        if (!$model) {
            return null;
        }

        return $model;
    }


}
